package com.sh;
import java.net.*;

public class UDPReceiver {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(11111); // 绑定接收端口
            byte[] buffer = new byte[1024];
            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet); // 阻塞等待数据
                // 解析数据（处理中文编码）
                String receivedData = new String(
                        packet.getData(), 0, packet.getLength(), "UTF-8"
                );
                InetAddress sourceIP = packet.getAddress();
                int sourcePort =packet.getPort();
                System.out.println("来自 " + sourceIP +"端口号："+sourcePort +" 的数据: " + receivedData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}